﻿using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace MinorAspNetCore.Server
{
    public class MinorHttpListenerServer : IServer
    {
        private readonly HttpListener _httpListener;
        private readonly string[] _urls;

        public MinorHttpListenerServer(params string[] urls)
        {
            _httpListener = new HttpListener();
            _urls = urls.Any() ? urls : new string[] { "http://localhost:5000/" };
        }

        public async Task StartAsync(RequestDelegate handler)
        {
            Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
            _httpListener.Start();
            Console.WriteLine("Server started and is listening on: {0}", string.Join(';', _urls));

            while (true)
            {
                var listenerContext = await _httpListener.GetContextAsync();
                var feature = new MinorHttpListenerFeature(listenerContext);
                var features = new MinorFeatureCollection()
                    .Set<IMinorHttpRequestFeature>(feature)
                    .Set<IMinorHttpResponseFeature>(feature);
                var httpContext = new MinorHttpContext(features);
                await handler(httpContext);
                listenerContext.Response.Close();
            }
        }
    }

    public static partial class Extensions
    {
        public static IMinorWebHostBuilder UseHttpListener(this IMinorWebHostBuilder builder, params string[] urls)
            => builder.UseServer(new MinorHttpListenerServer(urls));
    }
}